# -*- coding: utf-8 -*-
# @Author  : Pony
# @Time    : 2021/11/25 上午14:01

import os
import socket

def get_local_ip() -> str:
    """
    获取本地ipv4地址
    """
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('8.8.8.8', 80))
        addr, port = csock.getsockname()
        csock.close()
        return addr
    except socket.error:
        return "127.0.0.1"


IP1 = get_local_ip()
print(f'识别到宿主机ip为:{IP1}')
IP2 = input('如果识别的ip不正确，请输入正确的ip地址:')
if '.' not in IP2:
    IP = IP1
else:
    IP = IP2
print(f'最终ip为:{IP}')
BACKEND_PORT = '8008'  # 后端端口，与docker-compose.yml 保持一致
REDIS_PORT = '16379'  # redis端口，与docker-compose.yml 保持一致
# js中的robot_url　需要手动修改
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def update_config():
    """
    @desc 更新配置
    """
    print('------更新配置: 开始------')
    # 更新前段配置
    dist_name = 'dist'
    replace_js_path = os.path.join(BASE_DIR, 'compose', 'nginx', dist_name, 'static', 'js', 'config.js')
    file_data = ""
    with open(replace_js_path, "r", encoding="utf-8") as f:
        for line in f:
            if 'baseUrl' in line:
                line = f'    baseUrl: "http://{IP}:{BACKEND_PORT}",\n'
            elif 'socket_url' in line:
                line = f'    socket_url: "ws://{IP}:{BACKEND_PORT}",\n'
            file_data += line
    with open(replace_js_path, "w", encoding="utf-8") as f:
        f.write(file_data)

    # 更新环境变量
    web_env_path = os.path.join(BASE_DIR, 'backend', '.env')
    file_data = ""
    with open(web_env_path, "r", encoding="utf-8") as f:
        for line in f:
            if 'IP=' in line:
                line = f'IP={IP}\n'
            if 'REDIS_PORT=' in line:
                line = f'REDIS_PORT={REDIS_PORT}\n'
            if 'BACKEND_PORT=' in line:
                line = f'BACKEND_PORT={BACKEND_PORT}\n'
            file_data += line
    with open(web_env_path, "w", encoding="utf-8") as f:
        f.write(file_data)
    print('------更新配置: 成功------')


def deploy():
    """
    @desc 部署服务
    """
    print('------部署服务: 开始------')

    os.chdir(BASE_DIR)
    os.system('docker-compose down')
    os.chdir(BASE_DIR)
    os.system('docker-compose up -d')
    print('------部署服务: 成功------')


def set_boot_up():
    """
    @desc设置开机启动
    """
    with open('/etc/rc.local') as f:
        if '/usr/bin/python3 deploy.py' in f.read():
            return
    print('设置开机自启')
    os.system('sudo chmod 777 /etc/rc.local')
    os.system(f'echo cd {os.path.join(BASE_DIR, "scripts")} >> /etc/rc.local')
    os.system('echo "/usr/bin/python3 deploy.py" >> /etc/rc.local')


def main():
    # 更新配置
    update_config()
    # 部署服务
    deploy()
    # 设置开机启动
    # set_boot_up()


if __name__ == '__main__':
    main()
